package annotationService.application;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.Logger;
import java.util.zip.ZipInputStream;

import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

/**
 * 
 * @author Andres Westermann
 * Class for transferring KML documents
 */
public class KMLResource extends Resource {
	Logger log = Logger.getLogger(KMLResource.class.getSimpleName());
	final StringRepresentation NO_FOUND_REPR = new StringRepresentation(
			"Not found!");
	final StringRepresentation ERR_REPR = new StringRepresentation(
			"Something wrong!");
	private String xml;

	public KMLResource(Context context, Request request, Response response) {
		super(context, request, response);
		this.getVariants().add(new Variant(MediaType.TEXT_PLAIN));
		this.setAvailable(true);
		this.setModifiable(true);
		this.setNegotiateContent(true);
	}

	@Override
	/**
	 * representing after calling default get handle
	 */
	public Representation represent(Variant variant) throws ResourceException {
		log.info("representing after calling default get handle...");
		Representation result = null;
		if (variant.getMediaType().equals(MediaType.TEXT_PLAIN)) {
			String kmlURL = getRequest().getResourceRef().getQueryAsForm()
					.getQueryString();
			// handle query
			if (kmlURL != null && kmlURL.length() > 0) {
				if (kmlURL.contains("%3A%2F%2F")) {
					kmlURL = kmlURL.replace("%3A%2F%2F", "://");
				}
				if (kmlURL.contains("%2F")) {
					kmlURL = kmlURL.replaceAll("%2F", "/");
				}
				if (kmlURL.contains("%20")) {
					kmlURL = kmlURL.replaceAll("%20", " ");
				}
				try {
					this.xml = xmlRepresent(kmlURL);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.info(e.toString());
				}
				result = new StringRepresentation(this.xml, MediaType.TEXT_XML,
						Language.ALL, CharacterSet.UTF_8);
			} else {
				result = NO_FOUND_REPR;
			}
		}
		return result;
	}

	protected StringRepresentation callMethod(String method, String kmlURL) {
		if (kmlURL != null) {
			log.info("response:" + kmlURL);
			return new StringRepresentation(kmlURL, MediaType.APPLICATION_XML,
					Language.ALL, CharacterSet.UTF_8);
		} else {
			return ERR_REPR;
		}
	}

	/**
	 * return the XML as String
	 * 
	 * @param URL
	 * @return XML document as String
	 * @throws IOException
	 */
	public String xmlRepresent(String URL) throws IOException {
		Logger log = Logger.getLogger(KMLResource.class.getSimpleName());

		try {
			// Prepare the request
			if(URL.contains("QUEST%3BION")){
				URL = URL.replaceAll("QUEST%3BION", "?");
			}
			if (new Request(Method.GET, URL) != null) {
				Request request = new Request(Method.GET, URL);
				// Handle it using an HTTP client connector
				Client client = new Client(Protocol.HTTP);
				Response response = client.handle(request);
				String xmlString = (String)response.getEntity().getText();
				if(xmlString.contains("")){
					Response response2 = client.handle(request);
					ZipInputStream zin = new ZipInputStream(response2.getEntity().getStream());
					xmlString = zin.getNextEntry().getName();
				}
				return xmlString;
			} else {
				return "No page";
			}
		} catch (NullPointerException e) {
			return "No page";
		}
	}

}
